package hero.mps.inter_view;

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
    }
}
public class ReverseBetween {
    public static ListNode reverseBetween(ListNode listNode, int left, int right) {
        if (listNode == null ||  left == right) return listNode;
        ListNode dummy = new ListNode(0);
        dummy.next = listNode;
        ListNode prev = dummy;
        for (int i = 1; i < left; i++) {
            prev = prev.next;
        }
//        left 节点
        ListNode current = prev.next;
        ListNode current_next = current.next;
        for (int i = 0; i < right - left; i++) {
            current.next = current_next.next;
            current_next.next = prev.next;
            prev.next = current_next;
            current_next = current.next;
        }
        return dummy.next;
    }

    public static void printList(ListNode head) {
        ListNode cuur = head;
        while (cuur != null) {
            System.out.print(cuur.val + " ");
            cuur = cuur.next;
        }
        System.out.println();
    }
    public static void main(String[] args) {

        // 创建一个链表: 1 -> 2 -> 3 -> 4 -> 5
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        int left = 2, right = 4;
        ListNode result = reverseBetween(head, left, right);
        printList(result);
    }
}
